<template>
	<!--创建任务-->
	<view class="page-content">
		<scroll-view class="page-body" :scroll-top="scrollTop" scroll-y="true" @scrolltolower="loadmore()">
			<!--动态-->
			<template v-if="pageobj.datalist && pageobj.datalist.length > 0 ">
				<view class="body-box">
					<block v-for="(item,index) in pageobj.datalist" :key="index">
						<view class="box-li" @click.stop="checks(index,item.checked)" :style="{width:img_width + 'px'}">
							<image class="box-li-img" :src="item.url" :style="{width:img_width + 'px'}" mode="aspectFill"></image>
							<image class="box-li-checks"
								:src="item.checked?$mAssetsPath.icon_checked_on:$mAssetsPath.icon_checked"></image>
							<!--选择标签-->
							<view class="box-li-sel" v-if="item.num>0">
								<block v-for="(item2,index2) in item.selects" :key="index2">
									<view  v-if="item2.selects && item2.selects.length>0">
										<block v-for="(ite,ind) in item2.selects" :key="ind">
											<view class="sel-li" v-if="ite.selected">
												<view class="sel-li-name">{{ite.name}}</view>
												<image @tap.stop="todel(index,index2,ind,ite.selected)" class="sel-li-del"
													:src="$mAssetsPath.icon_sc5"></image>
											</view>
										</block>
									</view>
								</block>
							</view>
						</view>
					</block>
				</view>
				<!-- 上拉加载 -->
				<view class="det-con-more">
					<load-more :loadmore="load_more1"></load-more>
				</view>
			</template>
			<!--无数据-->
			<empty v-else no-full type="noData"></empty>
		</scroll-view>
		<view class="page-foot" v-if="pageType==='pro' && !show">
			<view class="page-foot-l" @click="toclass(show)">分类</view>
			<view class="page-foot-r" @click="confirm">确认</view>
		</view>
		<view class="page-foot2" v-else-if="(pageType==='pop' || pageType==='prop') && !show">
			<view class="page-foot-l" @click="toclass(show)">重置</view>
			<view class="page-foot-r" @click="confirm">分类</view>
		</view>
		<!--预览下拉框 -->
		<u-popup class="popup-content" mode='bottom' border-radius="16" v-model="show">
			<scroll-view class="menu-box" :scroll-y="true">
				<view class="box" v-for="(box,box_index) in pageobj.submenu" :key="box_index">
					<view class="title">{{box.name}}</view>
					<view class="labels">
						<view class="label" v-if="" style="margin-right:10rpx" :style="{width:lable_width + 'px'}"
							v-for="(label,label_index) in box.submenu" :key="label_index"
							@tap="selectRadioLabel(box_index,label_index)" :class="{'on':label.selected}">
							{{label.name}}
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="btn-box">
				<view class="reset" @tap="cancel(show)">取消</view>
				<view class="submit" @tap="confirm1">确定</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import wTit from '@/components/w-tit/w-tit-back-serch-add.vue'; //标题
	import loadMore from '@/components/uni-load-more/load-more.vue';
	import noteBookLi from '@/pages/components/note_book_li.vue';
	import {
		mapGetters,
		mapActions
	} from 'vuex';
	import {
		getProductAttrLists, //获取产品属性列表
		getProductCodingLists, //获取POP/道具编码列表
		uploadPictureAlbumImgArrs,
		getOssUploadsParams , //

	} from '@/common/api.js';
	export default {
		components: {
			loadMore,
			noteBookLi,
			wTit
		},
		data() {
			return {
				scrollTop: 0,
				noData: false,
				load_more1: '', //下拉加载文字
				load_sta: false, //是否是加载状态
				pageobj: {
					datalist: [],
					name: '单选',
					type: 'radio',
					submenu: [],
				},
				user_statu: {
					add_statu: false,
					replace_statu: false,
					stick_del_statu: false
				},
				system: {
					w: 0,
					h: 0,
					scale: 1,
					systemScale: 1,
				},
				show: false, //弹窗
				pageType: '', //pro-画册   pop-pop  prop-道具
				uploads: {
					company_id: '',
					type: '',
					product_album_id: '',
					img_list: []
				},
				pagedata: {
					company_id: 0,
					top_id: 0,
				},
				addType:'',
				task_id:'',
				selType:'',
				sourceType: ['album', 'camera'],
				chooseNum: 9,
				selects:[]
			}
		},
		computed: {
			...mapGetters(['companyInfo']),
			img_width() {
				return (this.system.w - 40) / 2;
			},
			lable_width() {
				return (this.system.w - (30 + 4 * 5)) / 4;
			}
		},
		onShow() {
			uni.getSystemInfo().then(res => {
				let system = res[1]
				this.system.scale = 667 / 375 //按照苹果留 375*667比例 其他型号手机等比例缩放 显示
				this.system.systemScale = system.windowWidth / 375 //按照苹果留 375*667比例 其他型号手机等比例缩放 显示
				this.system.w = system.windowWidth;
				this.system.h = system.windowHeight;
			})
			this.getdata();
		},
		onLoad(option) {
			console.log(222, option)
			this.pagedata.company_id = this.companyInfo.id;
			if (option.pageType) {
				this.pageType = option.pageType;
			}
			if (option.company_id) {
				this.uploads.company_id = option.company_id;
			}
			if (option.type) {
				this.uploads.type = option.type;
			}
			if (option.product_album_id) {
				this.uploads.product_album_id = option.product_album_id;
			}

			if (option.img_list) {
				//this.uploads.img_list = JSON.parse(option.img_list);
				this.pageobj.datalist = JSON.parse(option.img_list);
			}
			if(option.addType){
				this.addType = option.addType;
			}
			if(option.task_id){
				this.task_id = option.task_id;
			}
			if(option.selType){
				this.selType = option.selType;
			}
		},
		onNavigationBarButtonTap(e) {
			console.log(23, e)
			//0级增加
			if (e.index == 0) {
				this.chooseImages();
			}
		},
		methods: {
			//标题右侧图标1 add
			chooseImages() {
				let _self = this;
				this.uploads.type = 2;
				uni.chooseImage({
							count: this.chooseNum,
							sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
							sourceType: this.sourceType,
							success: (tempFilePaths) => {
								console.log('选择文件：', tempFilePaths)
								_self.getdata();
								if(tempFilePaths.tempFilePaths && tempFilePaths.tempFilePaths.length>0){
									tempFilePaths.tempFilePaths.forEach(item=>{
										let img_list = {
											url: '',
											checked:true,
											selects:JSON.parse(JSON.stringify(this.selects)),
											num:0
										}
										img_list.url = item;
										_self.pageobj.datalist.push(img_list)
									})
								}
								
								
								/* let _self = this;
								uni.showLoading({
									title: '上传中'
								});
								let uploadImgs = [];
								getOssUploadsParams().then(res => {
										if (res.code === 2000) {
											tempFilePaths.tempFilePaths.forEach((item, index) => {
													uploadImgs.push(new Promise((resolve, reject) => {
														let file_path = item;
														let filename = tempFilePaths.tempFiles[
															index];
														let suffix = "." + _self.getCaption(
															filename.path);
														let file_name = new Date().getTime() + Math
															.random().toString(
																36).substring(3, 20) + suffix
														console.log(333333, file_name, filename)
														//上传图片接口
														uni.uploadFile({
															url: res.data.host,
															filePath: file_path,
															fileType: 'image',
															name: 'file',
															formData: {
																name: file_path,
																'key': res.data.dir +
																	file_name,
																'policy': res.data.policy,
																'OSSAccessKeyId': res.data
																	.accessid,
																'success_action_status': '200',
																//让服务端返回200,不然，默认会返回204
																'signature': res.data
																	.signature,
															},
															success: (res2) => {
																resolve(res2);
																console.log(
																	'uploadImage success, res is:',
																	res2)
																let img_list = {
																	url: ''
																}
																img_list.url = res.data
																	.host + '/' + res
																	.data
																	.dir + file_name;
																_self.pageobj.datalist.push(img_list)
																console.log(666,
																	img_list)
															},
															fail: (err) => {
																console.log(err);
																reject(err);
															},
															complete: () => {
																//uni.hideLoading();
															}
														});
													}))
													Promise.all(uploadImgs).then((results) => { //执行所有需请求的接口
																uni.hideLoading();
															})
														.catch((res3, object) => {
															uni.hideLoading();
														});
													})
			
											}
										}) */
								}
							});
			},
			getCaption(obj) {
				var index = obj.lastIndexOf("\.");
				obj = obj.substring(index + 1, obj.length);
				return obj;
			},		
			//选中单选类label-UI状态
			selectRadioLabel(box_index, label_index) {
				let activeIndex = this.pageobj.submenu[box_index].submenu[label_index].name;
				console.log(JSON.stringify(this.pageobj.submenu[box_index].submenu[label_index]))
				console.log(123, activeIndex)
				if (this.pageobj.submenu && this.pageobj.submenu.length > 0) {
					this.pageobj.submenu.forEach((item, index) => {
						if (index === box_index) {
							if (item.submenu && item.submenu.length > 0) {
								item.submenu.forEach(item2 => {
									//this.$set(item2, 'selected', false)
									if (item2.name === activeIndex) {
										console.log(3, activeIndex)
										item2.selected = !item2.selected
									} else {
										item2.selected = false
									}
								})
							}
						}
					})
				}
				this.$forceUpdate();
			},
			//分类
			toclass(show) {
				if (this.pageType === 'pro') { //产品属性
					this.pagedata.top_id = 0;
					getProductAttrLists(this.pagedata).then(res => {
						if (res.code === 2000) {
							let pageobj = res.data;
							if (pageobj && pageobj.length > 0) {
								pageobj.forEach(item => {
									this.$set(item, 'submenu', Array);
									this.$set(item, 'checked', false);
									this.pagedata.top_id = item.id;
									getProductAttrLists(this.pagedata).then(res2 => {
										if (res2.code === 2000) {
											this.$nextTick(() => {
												item.submenu = res2.data;
												if(item.submenu && item.submenu.length>0){
													item.submenu.forEach(item2=>{
														this.$set(item2, 'selected', false)
													})
												}
											})
										}
									})
								})
							}
							this.pageobj.submenu = pageobj;
						}
					})
				
				} else if (this.pageType === 'pop') { //pop
					this.pagedata.top_id = 0;
					getProductCodingLists(this.pagedata).then(res => {
						if (res.code === 2000) {
							let pageobj = res.data;
							if (pageobj && pageobj.length > 0) {
								pageobj.forEach(item => {
									this.$set(item, 'submenu', Array);
									this.$set(item, 'isOpen', false);
								})
							}
							this.pageobj = pageobj;
						}
					})
				} else if (this.pageType === 'prop') { //prop
					this.pagedata.top_id = 0;
					getProductCodingLists(this.pagedata).then(res => {
						if (res.code === 2000) {
							let pageobj = res.data;
							if (pageobj && pageobj.length > 0) {
								pageobj.forEach(item => {
									this.$set(item, 'submenu', Array);
									this.$set(item, 'isOpen', false);
								})
							}
							this.pageobj = pageobj;
						}
					})
				}
				this.show = !show;
			},
			//选择
			checks(index, checked) {
				if (this.pageobj.datalist && this.pageobj.datalist.length > 0) {
					this.pageobj.datalist.forEach((item, ind) => {
						if (index === ind) {
							item.checked = !checked;
						}
					})
				}
			},
			//初始化数据
			getdata() {
				if (this.pageType === 'pro') { //产品属性
					this.pagedata.top_id = 0;
					getProductAttrLists(this.pagedata).then(res => {
						if (res.code === 2000) {
							this.selects = res.data.map((item)=>({
								...item,
								selects:[]
							})); 
							if (this.pageobj.datalist && this.pageobj.datalist.length > 0) {
								this.pageobj.datalist.forEach(item => {
									this.$set(item, 'checked', false)
									this.$set(item, 'num', 0)
									let selects = []
									this.$set(item,'selects',selects)
									item.selects = JSON.parse(JSON.stringify(this.selects))
								})
							}
						}
					})
				}
			},
			loadmore() {

			},
			//删除标签
			todel(index, index2, ind, selected) {
				console.log(5, index, ind, selected)
				console.log(5, this.pageobj.datalist)
				var datalist = this.pageobj.datalist;
				if (this.pageobj.datalist && this.pageobj.datalist.length > 0) {
					this.pageobj.datalist.forEach((item, i) => {
						if (index == i) {
							if (item.selects && item.selects.length > 0) {
								item.selects.forEach((ite, ii) => {
									if(index2 === ii){
										if(ite.selects && ite.selects.length>0){
											ite.selects.forEach((ite2,iii)=>{
												if (ind ===iii) {
													this.$set(ite2, 'selected', false);
												}
											})
										}
									}
								})
							}
						}
					})
				}
			},
			//确定
			async confirm() {
				if (this.pageType === 'pro') {
					//上传
					const resData = this.pageobj.datalist
					uni.showLoading({
						mask: true
					})
					const urls = []
					for (let i = 0; i < resData.length; i++) {
						/* if(resData[i].checked){
							const url = await this.uploadFile(resData[i].url, 'image', '.jpg')
							resData[i].url = url
							this.$forceUpdate()
						} */
						const url = await this.uploadFile(resData[i].url, 'image', '.jpg')
						resData[i].url = url
						this.$forceUpdate()
					}
					//参数转化
					let img_lists = [];
					if (this.pageobj.datalist && this.pageobj.datalist.length > 0) {
						this.pageobj.datalist.forEach(item => {
							let img_list = {
								url: '',
								product_attr_id: []
							}
							/* if (item.checked) {
								img_list.url = item.url
								if (item.selects && item.selects.length > 0) {
									item.selects.forEach(item2 => {
										if(item2.selects && item2.selects.length>0){
											item2.selects.forEach(item3 =>{
												if (item3.selected) {
													img_list.product_attr_id.push(item3.id)
												}
											})
										}
									})
								}
								img_lists.push(img_list)
							} */
							img_list.url = item.url
							if (item.selects && item.selects.length > 0) {
								item.selects.forEach(item2 => {
									if(item2.selects && item2.selects.length>0){
										item2.selects.forEach(item3 =>{
											if (item3.selected) {
												img_list.product_attr_id.push(item3.id)
											}
										})
									}
								})
							}
							img_lists.push(img_list)
						})
					}
					this.uploads.img_list = img_lists;
					console.log(111222,img_lists)
					this.uploads.type = 2;
					uploadPictureAlbumImgArrs(this.uploads).then(res => {
						uni.hideLoading()
						if (res.code === 2000) {
							uni.showToast({
								title: '设置成功！',
								icon: 'none',
								duration: 2000
							})
							if(this.addType === 'popadd'){
								if(this.uploads.img_list && this.uploads.img_list.length>0){
									this.uploads.img_list.forEach(item=>{
										this.$set(item,'id',0)
										if(res.data && res.data.length>0){
											res.data.forEach(item2=>{
												item.id = item2;
											})
										}
									})
								}
								uni.navigateTo({
									url:`/pages/user/batch?task_id=${this.task_id}&selType=${this.selType}&addType=${this.addType}&imglist=${JSON.stringify(this.uploads.img_list)}`
								})
								
							}else{
								this.$util.prePage().resdata();
								setTimeout(() => {
									uni.navigateBack();
								}, 500)
							}
						}
					}).catch(() => {
					uni.hideLoading()
				})

				} else if (this.pageType === 'pop' || this.pageType === 'prop') {
					uni.navigateTo({
						url: `/pages/user/batch?pageType=${this.pageType}`
					})
				}
			},
			// 上传文件
			uploadFile(file_path, fileType, type) {
				console.log('uploadFile', file_path);
				return new Promise((resolve, reject) => {
					//let suffix = "."+filename.extname;
					let file_name = new Date().getTime() + Math.random().toString(36).substring(3, 20) + type;
					getOssUploadsParams().then(res => {
						let uploadTask = uni.uploadFile({
							url: res.data.host,
							filePath: file_path,
							fileType,
							name: 'file',
							formData: {
								name: file_path,
								'key': res.data.dir + file_name,
								'policy': res.data.policy,
								'OSSAccessKeyId': res.data.accessid,
								'success_action_status': '200',
								//让服务端返回200,不然，默认会返回204
								'signature': res.data.signature,
							},
							success: (res2) => {
								console.log('upload-res', res2)
								// _self.objdata.person.img = res.data.host + '/' + res.data.dir + file_name;
								const url = res.data.host + '/' + res.data.dir + file_name;
								resolve(url)
							},
							fail: (err) => {
								console.log('uploadImage fail', err);
								uni.showModal({
									content: err.errMsg,
									showCancel: false
								});
								reject()
							}
						});
					})
				})
			},
			//下拉框确定
			confirm1() {
				console.log(1234, this.pageobj)
				let selected = []
				if (this.pageobj.datalist && this.pageobj.datalist.length > 0) {
					this.pageobj.datalist.forEach(item => {
						if (item.checked === true) {
							if(item.selects && item.selects.length>0){
								item.selects.forEach(item2=>{
									
									if (this.pageobj.submenu && this.pageobj.submenu.length > 0) {
										this.pageobj.submenu.forEach(item3=> {
											let item33 = JSON.parse(JSON.stringify(item3));
											item33.submenu.forEach((ite,ind) => {
												if(ite.selected){
													
													console.log(1,ite)
													if(ite.top_id === item2.id && item2.selects.length === 0){
														console.log(2)
														item2.selects.push(ite)
													}else if(ite.top_id === item2.id && item2.selects.length > 0){
														let selects = []
														selects.push(ite)
														console.log(3)
														item2.selects = selects
													}
												}
											})
										})
									}
								})
							}
						}
					})
				}
				if (this.pageobj.datalist && this.pageobj.datalist.length > 0) {
					this.pageobj.datalist.forEach(item => {
						if (item.checked === true) {
							if(item.selects && item.selects.length>0){
								item.selects.forEach(item2=>{
									if(item2.selects && item2.selects.length>0){
										item2.selects.forEach(item3=>{
											if(item.checked === true){
												item.num += 1;
											}
										})
									}
								})
							}
						}
					})
				}
				if (this.pageobj.datalist && this.pageobj.datalist.length > 0) {
					this.pageobj.datalist.forEach(item => {
						item.checked = false;
					})
				}
				
				console.log(12345, this.pageobj)
				this.show = false
			},
			//取消
			cancel() {
				this.show = false
			},
		}
	}
</script>

<style lang="scss">
	/* 下拉窗口 */
	.popup-content {
		display: flex;
		flex-direction: column;

		.btn-box {
			width: 100%;
			height: 100rpx;
			display: flex;
			flex-shrink: 0;
			flex-direction: row !important;
			align-items: center;
			font-size: 28rpx;
			font-weight: bold;
			line-height: 100rpx;
			color: $font-color-w;

			.reset {
				text-align: center;
				flex: 4;
				background: $uni-bg-color-red;
				color: $font-color-w;
			}

			.submit {
				text-align: center;
				flex: 6;
				background: $uni-but-bg-color;
			}
		}

		.menu-box {
			margin-top: 20rpx;
			width: 100%;
			height: calc(100% - 100rpx);
			flex-shrink: 1;

			.box {
				padding: 20rpx 30rpx;
				width: 100%;
				display: flex;
				flex-direction: column;

				.title {
					width: 100%;
					font-size: 28rpx;
					font-weight: 400;
					color: $font-color-3;
				}

				.labels {
					display: flex;
					flex-direction: row;
					flex-wrap: wrap;

					.label {
						border-radius: 4rpx;
						background: #f5f5f5;
						margin-top: 16rpx;
						display: flex;
						flex-direction: row;
						justify-content: center;
						align-items: center;
						font-size: 28rpx;
						font-weight: 400;
						line-height: 52rpx;
						color: $font-color-9;
						height: 52rpx;
					}

					.on {
						background: #CBE6FF !important;
						font-size: 28rpx;
						color: #198FFF !important;
					}
				}
			}
		}

		.footer {
			height: 100rpx;
			color: $font-color-r;
			font-size: 36rpx;
			text-align: center;
			line-height: 88rpx;
			background: $uni-bg-color;
			margin-right: 50rpx;
		}
	}

	.page-content {
		width: 100vw;
		height: 100%;
		background: $uni-bg-color;
		border-top: 1rpx solid #f5f5f5;

		.page-foot {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 100rpx;
			display: flex;
			align-items: center;

			.page-foot-l {
				flex: 6;
				text-align: center;
				background: $uni-bg-color-red;
				line-height: 100rpx;
				font-size: 32rpx;
				font-weight: bold;
				color: $font-color-w;
			}

			.page-foot-r {
				flex: 4;
				text-align: center;
				background: $uni-but-bg-color;
				line-height: 100rpx;
				font-size: 32rpx;
				font-weight: bold;
				color: $font-color-w;
			}
		}

		.page-foot2 {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			height: 100rpx;
			display: flex;
			align-items: center;

			.page-foot-l {
				flex: 4;
				text-align: center;
				background: $uni-bg-color-red;
				line-height: 100rpx;
				font-size: 32rpx;
				font-weight: bold;
				color: $font-color-w;
			}

			.page-foot-r {
				flex: 7;
				text-align: center;
				background: $uni-but-bg-color;
				line-height: 100rpx;
				font-size: 32rpx;
				font-weight: bold;
				color: $font-color-w;
			}
		}

		.page-body {
			display: flex;
			height: 100%;

			.body-box {
				display: flex;
				flex-wrap: wrap;
				padding: 30rpx;

				.box-li {
					border-radius: 10rpx;
					position: relative;
					align-items: center;
					margin-right: 20rpx;
					margin-bottom: 30rpx;

					.box-li-img {
						width: 338rpx;
						height: 436rpx;
					}

					.box-li-checks {
						position: absolute;
						right: 30rpx;
						top: 30rpx;
						width: 42rpx;
						height: 42rpx;
						border-radius: 21rpx;
					}

					.box-li-sel {
						position: absolute;
						top: 140rpx;
						padding: 20rpx;
						left: 0rpx;
						right: 0rpx;
						bottom: 0rpx;
						display: flex;
						flex-wrap: wrap;
						background: rgba(0, 0, 0, .5);

						.sel-li {
							height: 44rpx;
							display: flex;
							margin-right: 20rpx;
							margin-bottom: 30rpx;
							position: relative;

							.sel-li-name {
								height: 44rpx;
								background: #FFFFFF;
								border-radius: 8rpx;
								font-size: 30rpx;
								line-height: 44rpx;
								color: $font-color-3;
								padding: 0 16rpx;
							}

							.sel-li-del {
								position: absolute;
								width: 26rpx;
								height: 26rpx;
								right: -13rpx;
								top: -13rpx;
							}
						}
					}
				}

				.box-li:nth-of-type(2n) {
					margin-right: 0rpx;
					margin-bottom: 30rpx;
				}
			}
		}
	}
</style>
